﻿using DAL.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL.JSGN
{
    public class AttachmentDAL
    {
        private readonly DataContext _dataContext;

        public AttachmentDAL(DataContext dataContext)
        {
            _dataContext = dataContext;
        }

        public async Task CreateAsync(IEnumerable<Attachment> entities)
        {
            foreach (var item in entities)
            {
                await CreateAsync(item);
            }
        }

        public async Task CreateAsync(Attachment entity)
        {
            _dataContext.Entry(entity).State = EntityState.Added;
        }

        public async Task SaveChagnesAsync()
        {
            await _dataContext.SaveChangesAsync();
        }

        public async Task<IEnumerable<Attachment>> ListAsync(Guid businessId, string option = null)
        {
            var id = businessId.ToString();
            var query = from q in _dataContext.Attachments.AsNoTracking()
                        where q.BusinessId == id
                        select q;
            if (!string.IsNullOrEmpty(option)) query = query.Where(x => x.Option == option);
            return await query.ToListAsync();
        }

        public async Task<Attachment> GetAsync(Guid id)
        {
            return await _dataContext.Attachments.FindAsync(id);
        }

        public async Task DeleteAsync(IEnumerable<Attachment> entities)
        {
            foreach (var item in entities)
            {
                await DeleteAsync(item);
            }
        }

        public async Task DeleteAsync(Attachment entity)
        {
            _dataContext.Entry(entity).State = EntityState.Deleted;
        }

        public async Task DeleteAsync(string businessId)
        {
            var entities = await _dataContext.Attachments.Where(x => x.BusinessId == businessId).ToListAsync();
            await DeleteAsync(entities);
        }
    }
}
